using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

public class Log
{
	private static BackgroundWorker worker = new BackgroundWorker();

	private static string logFileName;

	private static List<string> listLog = new List<string>();

	private static int writeCount = 0;

	public static DateTime Now
	{
		get
		{
			return DateTime.Now;
		}
	}

	public static void Init(string folder)
	{
		logFileName = folder + "Log" + Now.ToString("yyyyMMdd") + ".txt";
		worker.WorkerReportsProgress = true;
		worker.WorkerSupportsCancellation = true;
		worker.DoWork += worker_DoWork;
		worker.RunWorkerCompleted += worker_RunWorkerCompleted;
	}

	private static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
	{
		if (listLog.Count > 0)
		{
			Run();
		}
	}

	private static void worker_DoWork(object sender, DoWorkEventArgs e)
	{
		while (listLog.Count > 0)
		{
			try
			{
				StringBuilder stringBuilder = new StringBuilder();
				int num = listLog.Count();
				for (int i = 0; i < num; i++)
				{
					stringBuilder.AppendLine(listLog[i]);
				}
				File.AppendAllText(logFileName, stringBuilder.ToString(), Encoding.UTF8);
				listLog.RemoveRange(0, num);
				writeCount = 5;
				Thread.Sleep(50);
			}
			catch (Exception)
			{
				writeCount++;
			}
			finally
			{
				if (writeCount >= 5)
				{
					Thread.Sleep(100);
					writeCount = 0;
				}
			}
		}
	}

	public static void WriteLine(string content, bool timestamp = true)
	{
		string text = Now.ToString("yyyy/MM/dd HH:mm:ss.fff");
		if (timestamp)
		{
			content = text + ":" + content;
		}
		if (!string.IsNullOrEmpty(logFileName))
		{
			listLog.Add(content);
			Run();
		}
	}

	private static void Run()
	{
		Task.Factory.StartNew(delegate
		{
			while (true)
			{
				try
				{
					if (!worker.IsBusy)
					{
						worker.RunWorkerAsync();
					}
					break;
				}
				catch (Exception)
				{
				}
				Thread.Sleep(100);
			}
		});
	}
}
